﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :prefill-person="prefillPerson" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>请假出差信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_LeaveType_FormItem"
								prop="Entity.LeaveType"
								:rules="[{ required: true, message: '类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="类型" tooltip="请假/出差" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.LeaveType" clearable class="width100">
									<el-option v-for="item in LEAVE_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.LeaveType === '出差'">
							<el-form-item ref="Entity_AffectsAttendance_FormItem" prop="Entity.AffectsAttendance">
								<template #label>
									<WtmLabelTooltip label="是否影响考勤" tooltip="是否影响考勤统计" />
								</template>
								<el-switch v-model="stateData.vmModel.Entity.AffectsAttendance" active-text="是" inactive-text="否"></el-switch>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StartTime_FormItem"
								prop="Entity.StartTime"
								:rules="[{ required: true, message: '开始时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开始时间" tooltip="开始时间" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.StartTime"
									type="datetime"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择开始时间"
									format="YYYY-MM-DD HH:00"
									value-format="YYYY-MM-DD HH:00:00"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EndTime_FormItem"
								prop="Entity.EndTime"
								:rules="[{ required: true, message: '结束时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="结束时间" tooltip="结束时间" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.EndTime"
									type="datetime"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择结束时间"
									format="YYYY-MM-DD HH:00"
									value-format="YYYY-MM-DD HH:00:00"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Days_FormItem" prop="Entity.Days" :rules="[{ required: true, message: '天数为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="天数" tooltip="天数" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.Days"
									:disabled="true"
									class="width100"
									placeholder="系统自动计算"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason" :rules="[{ required: true, message: '事由为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="事由" tooltip="请假/出差事由" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Reason"
									type="textarea"
									:rows="2"
									clearable
									class="width100"
									placeholder="请输入请假/出差事由"
								></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
								<template #label>
									<WtmLabelTooltip label="证明文件" tooltip="上传请假/出差证明文件" />
								</template>
								<wtm-upload-file
									v-model="stateData.vmModel.Entity.SupportingDocumentId"
									:allowed-types="['application/pdf', 'image/jpeg', 'image/png', 'image/jpg']"
									clearable
									:multi="false"
								></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, watch, type ComponentInternalInstance } from 'vue';
import { SysDailyLeaveRequestBillApi as api } from '/@/views/daily/sysdailyleaverequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysDailyLeaveRequestBillVm } from '/@/views/daily/sysdailyleaverequestbill/api/interface';
import { IViewModel } from '/@/types/common';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
	IN_AUDIT: '审核中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
	COMPLETED: '已完成',
	CANCELLED: '已取消',
} as const;

const LEAVE_TYPE_OPTIONS = [
	{ value: '请假', label: '请假' },
	{ value: '出差', label: '出差' },
] as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const API_ENDPOINTS = {
	GROUPS: '/api/SysDailyLeaveRequestBill/GetSysGroups',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 动态表单验证规则
const formRules = computed(() => {
	const rules: Record<string, any[]> = {
		'Entity.PersonId': [{ required: true, message: '请选择员工', trigger: 'change' }],
		'Entity.LeaveType': [{ required: true, message: '请选择类型', trigger: 'change' }],
		'Entity.StartTime': [{ required: true, message: '请选择开始时间', trigger: 'change' }],
		'Entity.EndTime': [{ required: true, message: '请选择结束时间', trigger: 'change' }],
		'Entity.Days': [{ required: true, message: '请输入天数', trigger: 'blur' }],
	};

	return rules;
});

// 初始化表单数据
const stateData = reactive<IViewModel<ISysDailyLeaveRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			LeaveType: null,
			StartTime: null,
			EndTime: null,
			Days: null,
			Reason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			SupportingDocumentId: [],
			AffectsAttendance: false,
		} as any, // 使用类型断言来支持额外字段
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysGroups: [] as any[],
});

// 添加临时字段用于员工选择
const personId = ref<string | null>(null);
const orgId = ref<string | null>(null);

// 日期限制：前后60天
const disabledDate = computed(() => {
	return (time: Date) => {
		const today = new Date();
		const sixtyDaysAgo = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000);
		const sixtyDaysLater = new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000);
		return time < sixtyDaysAgo || time > sixtyDaysLater;
	};
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canSubmit = computed(
	() =>
		stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT &&
		(!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING)
);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove && isInAudit.value);

// 员工回显数据
const prefillPerson = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.PersonId && entity.Name && entity.StaffNo) {
		return {
			ID: entity.PersonId,
			Name: entity.Name,
			StaffNo: entity.StaffNo,
		};
	}
	return null;
});

// 监听开始时间和结束时间变化，自动计算天数
watch(
	[() => stateData.vmModel.Entity.StartTime, () => stateData.vmModel.Entity.EndTime],
	([startTime, endTime]) => {
		if (startTime && endTime) {
			const start = new Date(startTime);
			const end = new Date(endTime);

			// 确保结束时间不早于开始时间
			if (end >= start) {
				// 计算实际时间差（精确到小时）
				const timeDiff = end.getTime() - start.getTime();
				// 按小时计算天数，保留2位小数
				const hoursDiff = timeDiff / (1000 * 3600);
				const daysDiff = Math.round((hoursDiff / 24) * 100) / 100;
				stateData.vmModel.Entity.Days = daysDiff;
			} else {
				// 如果结束时间早于开始时间，清空天数
				stateData.vmModel.Entity.Days = null;
			}
		} else {
			// 如果任一时间为空，清空天数
			stateData.vmModel.Entity.Days = null;
		}
	},
	{ immediate: true }
);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then(() => handleSuccess(true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = null;
		stateData.vmModel.Entity.Name = null;
		stateData.vmModel.Entity.OrgId = null;
		stateData.vmModel.Entity.GroupId = null;
	}
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false // 保存后不关闭弹窗
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			// 提交前设置状态
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.FORMAL;
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true // 提交后关闭弹窗
	);
};

// 同意
const onAgree = () => {
	handleApproval(ACTIONS.AGREE);
};

// 拒绝
const onDeny = () => {
	handleApproval(ACTIONS.REJECT);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [groups, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (entityData.status === 'fulfilled') other.setValue(stateData.vmModel, entityData.value);
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !isInAudit.value, // 非审批状态时显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value && !isInAudit.value, // 草稿状态且非审批时显示提交
		},
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: canApprove.value, // 有审批权限时显示同意
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: canApprove.value, // 有审批权限时显示拒绝
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
